import React, { useRef, useState } from 'react';
import { Button, Tabs, Form, Checkbox, Divider, message } from 'antd';
import {
  DrawerForm,
  ProFormText,
  ProFormTextArea,
  ProFormGroup,
  ProColumns,
  EditableProTable,
  EditableFormInstance,
  ProFormSelect,
  ProFormRadio,
  ProFormTreeSelect,
  ProFormDependency,
} from '@ant-design/pro-components';
import { find, isArray } from 'lodash';
import { convertDict, convertTree, transToSelect } from '@/app/common/utils';
import { DefaultOptionType } from 'antd/lib/select';

const { TabPane } = Tabs;

interface DataSourceType {
  [x: string]: any;
}

export default function EditTableCol(props: {
  record: Record<string, any>;
  optionselect: Record<string, any>[];
  tree: Record<string, any>[];
}) {
  // 表格行数据
  const [rows, setRows] = useState([]);
  const [info, setInfo] = useState({});
  const [tables, setTables] = useState([]);
  // 默认编辑行
  const [editableKeys, setEditableKeys] = useState<string[]>([]);
  const [form] = Form.useForm<Record<string, any>>();
  const editableFormRef = useRef<EditableFormInstance>();
  // 字段列信息
  const [columnData, setColumnData] = useState<Record<string, any>[]>();

  // 自定义checkbox
  const customCheckbox = (_schema: any, config: any) => {
    const { record } = config;
    const dataIndex = isArray(_schema.dataIndex) ? _schema.dataIndex[0] : _schema.dataIndex;
    return (
      <Checkbox
        name={record[dataIndex]}
        onChange={v => {
          editableFormRef.current.setRowData(_schema.index, {
            [dataIndex]: v.target.checked === true ? '1' : undefined,
          });
        }}
        checked={record[dataIndex] === '1'}
      />
    );
  };

  // 转换rows 为select数据类型
  const selectForRows = () => {
    return rows.map(d => {
      return {
        label: `${d.columnName}: ${d.columnComment}`,
        value: d.columnName,
      };
    });
  };

  // 列表字段参数
  const columns: ProColumns<DataSourceType>[] = [
    {
      title: '序号',
      dataIndex: 'sort',
      valueType: 'index',
      editable: false,
      key: 'sort',
      width: 60,
    },
    {
      title: '',
      dataIndex: 'columnId',
      key: 'columnId',
      editable: false,
      hideInTable: true,
    },
    {
      title: '字段列名',
      dataIndex: 'columnName',
      key: 'columnName',
      editable: false,
    },
    {
      title: '字段描述',
      key: 'columnComment',
      dataIndex: 'columnComment',
      ellipsis: true,
      width: 200,
    },
    {
      title: '物理类型',
      key: 'columnType',
      dataIndex: 'columnType',
      editable: false,
    },
    {
      title: 'java类型',
      key: 'javaType',
      dataIndex: 'javaType',
      valueType: 'select',
      valueEnum: {
        String: {
          text: 'String',
        },
        Long: {
          text: 'Long',
        },
        Integer: {
          text: 'Integer',
        },
        Double: {
          text: 'Double',
        },
        BigDecimal: {
          text: 'BigDecimal',
        },
        Date: {
          text: 'Date',
        },
        Boolean: {
          text: 'Boolean',
        },
      },
    },
    {
      title: 'java属性',
      key: 'javaField',
      dataIndex: 'javaField',
    },
    {
      title: '插入',
      dataIndex: 'isInsert',
      key: 'isInsert',
      width: 60,
      renderFormItem: customCheckbox,
    },
    {
      title: '编辑',
      key: 'isEdit',
      dataIndex: 'isEdit',
      width: 60,
      renderFormItem: customCheckbox,
    },
    {
      title: '列表',
      key: 'isList',
      dataIndex: 'isList',
      width: 60,
      renderFormItem: customCheckbox,
    },
    {
      title: '查询',
      key: 'isQuery',
      dataIndex: 'isQuery',
      width: 60,
      renderFormItem: customCheckbox,
    },
    {
      title: '查询方式',
      key: 'queryType',
      dataIndex: 'queryType',
      valueType: 'select',
      valueEnum: {
        EQ: {
          text: '等于(==)',
        },
        NE: {
          text: '不等于(!=)',
        },
        GT: {
          text: '大于(>)',
        },
        GTE: {
          text: '大于(>=)',
        },
        LT: {
          text: '小于(<)',
        },
        LTE: {
          text: '小于等于(<=)',
        },
        LIKE: {
          text: '模糊(like)',
        },
        BETWEEN: {
          text: '范围(BETWEEN)',
        },
      },
    },
    {
      title: '必填',
      key: 'isRequired',
      dataIndex: 'isRequired',
      renderFormItem: customCheckbox,
      width: 60,
    },
    {
      title: '显示类型',
      key: 'htmlType',
      dataIndex: 'htmlType',
      // input文本框、textarea文本域、select下拉框、checkbox复选框、radio单选框、datetime日期控件、image图片上传控件、upload文件上传控件、editor富文本控件）
      valueType: 'select',
      valueEnum: {
        input: {
          text: '文本框',
        },
        textarea: {
          text: '文本域',
        },
        select: {
          text: '下拉框',
        },
        checkbox: {
          text: '复选框',
        },
        radio: {
          text: '单选框',
        },
        datetime: {
          text: '日期控件',
        },
        image: {
          text: '图片上传控件',
        },
        upload: {
          text: '文件上传控件',
        },
      },
    },
    {
      title: '字典类型',
      key: 'dictType',
      dataIndex: 'dictType',
      valueType: 'select',
      width: 200,
      valueEnum: {
        ...convertDict(props.optionselect),
      },
    },
  ];

  return (
    <DrawerForm<Record<string, any>>
      key="gen-tables"
      drawerProps={{
        maskClosable: false,
      }}
      submitTimeout={1000}
      form={form}
      title={`编辑生成代码列`}
      width="80%"
      initialValues={{
        rows,
        info,
      }}
      onFinish={async (value: { info: any }) => {
        const body = { ...(value.info as any), columns: columnData || rows };
        const res = await $put('/tool/gen', body);
        const isSuccess = res.code === 200;
        isSuccess && message.success(res.msg);
        return isSuccess;
      }}
      trigger={<Button type="link">编辑</Button>}
      request={async () => {
        const res = await $get(`/tool/gen/${props.record.tableId}`);
        if (res.code === 200) {
          setRows(res.data.rows);
          setInfo(res.data.info);
          setTables(res.data.tables);
          setEditableKeys(res.data.rows.map((d: { columnId: any }) => d.columnId));
        }
        return {};
      }}
    >
      <Tabs key="info">
        <TabPane tab="基本信息" key="basic" tabKey="basic" forceRender>
          <ProFormGroup labelLayout="inline">
            <ProFormText required width="xl" name={['info', 'tableName']} label="表名称" />
            <ProFormText required width="xl" name={['info', 'tableComment']} label="表描述" />
          </ProFormGroup>
          <ProFormGroup>
            <ProFormText required width="xl" name={['info', 'className']} label="实体类名称" />
            <ProFormText required width="xl" name={['info', 'functionAuthor']} label="作者" />
          </ProFormGroup>
          <ProFormTextArea width="xl" name={['info', 'remark']} label="备注" />
        </TabPane>
        <TabPane tab="字段信息" key="field" tabKey="field" forceRender>
          <EditableProTable
            editableFormRef={editableFormRef}
            rowKey="columnId"
            value={rows}
            columns={columns}
            recordCreatorProps={false}
            editable={{
              type: 'multiple',
              editableKeys,
              onValuesChange(_record, dataSource) {
                setColumnData(dataSource);
              },
            }}
          />
        </TabPane>
        <TabPane tab="生成信息" key="gen-info" tabKey="gen-info" forceRender>
          <ProFormGroup labelLayout="inline">
            <ProFormSelect
              required
              width="xl"
              name={['info', 'tplCategory']}
              label="表模板"
              // 使用的模板（crud单表操作 tree树表操作 sub主子表操作）
              options={[
                {
                  label: 'crud单表操作',
                  value: 'crud',
                },
                {
                  label: 'tree树表操作',
                  value: 'tree',
                },
                {
                  label: 'sub主子表操作',
                  value: 'sub',
                },
              ]}
            />
            <ProFormText required width="xl" name={['info', 'packageName']} label="生成包路径" />
            <ProFormText required width="xl" name={['info', 'moduleName']} label="生成模块名" />
          </ProFormGroup>
          <ProFormGroup>
            <ProFormText required width="xl" name={['info', 'businessName']} label="生成业务名" />
            <ProFormText required width="xl" name={['info', 'functionName']} label="生成功能名" />
            <ProFormTreeSelect
              label="上级菜单"
              required
              width="xl"
              name={['info', 'parentMenuId']}
              fieldProps={{
                treeData: convertTree(props.tree),
              }}
            />
          </ProFormGroup>
          <ProFormRadio.Group
            name={['info', 'genType']}
            label="生成代码方式"
            options={[
              {
                label: 'zip',
                value: '0',
              },
              {
                label: '自定义系统路径',
                value: '1',
              },
            ]}
          />
          <ProFormDependency name={['info', 'genType']} ignoreFormListField>
            {({ info }) => {
              if (info.genType === '1') {
                return (
                  <ProFormText required width="xl" name={['info', 'genPath']} label="自定义路径" />
                );
              }
            }}
          </ProFormDependency>
          <ProFormDependency name={['info', 'tplCategory']} ignoreFormListField>
            {({ info }, _form) => {
              if (info.tplCategory === 'crud') {
                return '';
              }
              return (
                <>
                  <Divider orientation="left" plain>
                    其他信息
                  </Divider>
                  {info.tplCategory === 'tree' ? (
                    <>
                      <ProFormGroup>
                        <ProFormSelect
                          required
                          width="xl"
                          name={['info', 'treeCode']}
                          label="树编码字段"
                          options={selectForRows()}
                        />
                        <ProFormSelect
                          required
                          width="xl"
                          name={['info', 'treeParentCode']}
                          label="树父编码字段"
                          options={selectForRows()}
                        />
                      </ProFormGroup>
                      <ProFormSelect
                        required
                        width="xl"
                        name={['info', 'treeName']}
                        label="树名称字段"
                        options={selectForRows()}
                      />
                    </>
                  ) : (
                    ''
                  )}
                  {info.tplCategory === 'sub' ? (
                    <>
                      <ProFormGroup>
                        <ProFormSelect
                          required
                          width="xl"
                          name={['info', 'subTableName']}
                          label="关联父表的表名"
                          fieldProps={{
                            onChange() {
                              _form.setFieldValue(['info', 'subTableFkName'], undefined);
                            },
                          }}
                          options={transToSelect(tables, 'tableComment', 'tableName')}
                        />
                        <ProFormDependency name={['info', 'subTableName']}>
                          {({ info }) => {
                            const item = find(tables, { tableName: info.subTableName });
                            let opt: string[] | DefaultOptionType[] = [];
                            if (item) {
                              opt = transToSelect(item.columns, 'columnComment', 'columnName');
                            }
                            return (
                              <>
                                <ProFormSelect
                                  required
                                  width="xl"
                                  name={['info', 'subTableFkName']}
                                  label="本表关联父表的外键名"
                                  options={opt}
                                />
                              </>
                            );
                          }}
                        </ProFormDependency>
                      </ProFormGroup>
                    </>
                  ) : (
                    ''
                  )}
                </>
              );
            }}
          </ProFormDependency>
        </TabPane>
      </Tabs>
    </DrawerForm>
  );
}
